package com.hhq.core;

import java.util.Map;
import java.util.TreeMap;


/**
 * 封装请求的类
 */
public class Req {

    public String method;   // 方法 GET POST
    public String url;   // 不带参数的url
    public String fullUrl;   // 带参数的URL
    public String version;    
    public Map<String, String> params=new TreeMap<>();  // URL 参数
    public Map<String, String> headers=new TreeMap<>();  // HTTP 请求头
    public String body = "";

    public Req(String pack){
        String lines[] = pack.split("\r\n");
        int i;
        i = 0;
        boolean headerFlag = true;
        boolean isFirstBody = true;
        for(String line : lines){
            if ( i == 0){
                i++;
                dealFirstLine(line);
            }else if ( line.equals("")){
                headerFlag = false;
                continue;
            }else if(headerFlag ){
                dealHeaders(line);
            }else{
                if (isFirstBody){
                    body += line;
                    isFirstBody = false;
                }else{
                    body += "\r\n"+line;
                }
            }
        }
    }
    private void dealFirstLine(String line){
        String[] tmps = line.split(" ");
        if (tmps.length != 3){
            dealException(line);
        }
        method = tmps[0];
        fullUrl = tmps[1];
        version = tmps[2];
        if(fullUrl.contains("?")){  //  /get_user?name=hhq&age=15
            String[] args = fullUrl.split("?");
            url = args[0];
            String[] args2 = args[1].split("&");
            for(String one: args2){
                String[] keyValue = one.split("=");
                params.put(keyValue[0], keyValue[1]);
            }
        }else{
            url = fullUrl;
        }
    }
    private void dealHeaders(String line){
        String[] tmps = line.split(":");
        if (tmps.length < 2){
            dealException(line);
        }else{
            String value="";
            for(int i=1; i<tmps.length; i++){
                value += ":" + tmps[i].trim();
            }
            headers.put(tmps[0].trim(),value.substring(1));
        }
    }

    private void dealException(String pack){
        System.out.println("解析http请求报文出错，出错的报文内容如下: [[");
        System.out.println(pack);
        System.out.println("]]END");
        throw new  RuntimeException();
    }
}